﻿using System;
using System.Collections;
using System.Collections.Generic;
using CalcSharp.Core;
using CalcSharp.Core.Containers;
using CalcSharp.Core.Plugin;

namespace plug_uconv
{
    public class uconv : ICMDPlugin
    {

        private IPluginHost host;
        private xmlreader xs;

        public Dictionary<string, string> autocomplete
        {
            get
            {
                Dictionary<string, string> elements = xs.GetAutoCompItems();
                elements.Add("Prefixes", "pico;nano;mikro;mili;centi;deci;deka;hekto;kilo;mega;giga;tera;peta;exa");
                return elements;
            }
        }

        public Tresult Run(ArrayList parameters)
        {
            Tresult res = new Tresult();
            double val = Convert.ToDouble(parameters[0]);
            string src, dest;
            src = (parameters[1] as string);
            dest = (parameters[2] as string);

            double srcmul, destmul, stdval;

            string[] srcpart = PrefixParser.splitprefix(src);
            string[] destpart = PrefixParser.splitprefix(dest);

            srcmul = Math.Pow(10, (double)PrefixParser.parseprefix(srcpart[0]));

            val = val * srcmul;

            if (xs.CanConvert(xs[srcpart[1]], xs[destpart[1]]))
            {

                stdval = xs.Conv2Std(xs[srcpart[1]], val);

                destmul = Math.Pow(10, -1 * (double)PrefixParser.parseprefix(destpart[0]));
                res.floatingpt = destmul * xs.Conv2unit(xs[destpart[1]], stdval);
            }
            else throw new CSException("Canot convert, because source and destination units are not in the same category");

            return res;
        }

        public string Name
        {
            get { return "UCONV"; }
        }

        public string Help
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        public IPluginHost Host
        {
            get
            {
                return host;
            }
            set
            {
                this.host = value;
                xs = new xmlreader();
                host.Register(this);
            }
        }
    }
}
